import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class LC_637 {
    public List<Double> averageOfLevels(LC_144.TreeNode root) {
        List<Double> result = new ArrayList<>();
        Queue<LC_144.TreeNode> que = new LinkedList<>();
        int size = 1;
        if(root == null){
            return result;
        }
        que.offer(root);
        while(!que.isEmpty()){
            List<Integer> list = new ArrayList<>();
            int len = size;
            size = 0;
            while(len != 0){
                len--;
                LC_144.TreeNode node = que.poll();
                list.add(node.val);
                if(node.left != null){
                    size++;
                    que.offer(node.left);
                }
                if(node.right != null){
                    size++;
                    que.offer(node.right);
                }
            }
            double sum = 0;
            for(int i = 0; i < list.size(); i++){
                sum += list.get(i);
            }
            sum/=list.size();
            result.add(sum);
        }
        return result;
    }
}
